package TCP.Demo2;

// MultiThreadChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;

public class MultiThreadChatServer {
    // 存储所有客户端的输出流
    private static final List<PrintWriter> clientOutputStreams = new ArrayList<>();

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("聊天服务器已启动，等待客户端连接...");

            while (true) {
                // 接受客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("新客户端已连接：" + clientSocket.getInetAddress());

                // 为每个客户端创建输出流并添加到列表
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                clientOutputStreams.add(writer);

                // 为每个客户端创建一个线程处理输入
                Thread clientHandler = new Thread(new ClientHandler(clientSocket));
                clientHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 客户端处理类，处理每个客户端的输入
    private static class ClientHandler implements Runnable {
        private final BufferedReader reader;

        public ClientHandler(Socket clientSocket) {
            try {
                reader = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void run() {
            String message;
            try {
                // 读取客户端消息并广播
                while ((message = reader.readLine()) != null) {
                    System.out.println("收到消息：" + message);
                    broadcastMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 广播消息给所有客户端
        private void broadcastMessage(String message) {
            for (PrintWriter writer : clientOutputStreams) {
                writer.println(message);
                writer.flush();
            }
        }
    }
}
